package com.jingxuan.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.NonNull;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.io.File;

/**
 * Web配置类
 */
@Slf4j
@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Value("${file.upload-dir:uploads/}")
    private String uploadDir;

    // CORS配置已移至CorsConfig类，使用CorsFilter方式配置

    /**
     * 静态资源配置
     */
    @Override
    public void addResourceHandlers(@NonNull ResourceHandlerRegistry registry) {
        String path = uploadDir;
        File uploadFile = new File(path);
        
        // 如果是相对路径，转换为绝对路径
        if (!uploadFile.isAbsolute()) {
            path = System.getProperty("user.dir") + File.separator + path;
            uploadFile = new File(path);
        }

        // 确保目录存在
        if (!uploadFile.exists()) {
            boolean created = uploadFile.mkdirs();
            if (created) {
                log.info("创建上传目录: {}", uploadFile.getAbsolutePath());
            } else {
                log.error("创建上传目录失败: {}", uploadFile.getAbsolutePath());
            }
        }

        // 获取绝对路径并规范化
        String absolutePath = uploadFile.getAbsolutePath();
        if (!absolutePath.endsWith(File.separator)) {
            absolutePath += File.separator;
        }

        // 映射 /uploads/** 到文件系统路径
        // 使用 file:/// 协议（注意三个斜杠）
        String fileUrl = "file:///" + absolutePath.replace("\\", "/");
        
        // 修正可能的多个斜杠问题
        if (fileUrl.contains("file:////")) {
            fileUrl = fileUrl.replace("file:////", "file:///");
        }

        log.info("配置静态资源映射: /uploads/** -> {}", fileUrl);
        registry.addResourceHandler("/uploads/**")
                .addResourceLocations(fileUrl);
    }

}
